package com.erp.framework.shiro.service;


import com.erp.framework.constant.ConfigConstants;
import com.erp.framework.constant.Constants;
import com.erp.framework.constant.UserConstants;
import com.erp.framework.domain.SysUser;
import com.erp.framework.exception.user.UserBlockedException;
import com.erp.framework.exception.user.UserNotExistsException;
import com.erp.framework.exception.user.UserPasswordNotMatchException;
import com.erp.framework.service.ISysUserService;
import com.erp.framework.util.StringUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 登录校验方法
 *
 * @author erp
 */
@Component
public class SysLoginService {

    @Autowired
    private ISysUserService userService;

    /**
     * 登录
     */
    public SysUser login(String username, String password) {
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            throw new UserPasswordNotMatchException();
        }

        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            throw new UserPasswordNotMatchException();
        }

        // 查询用户信息
        SysUser user = userService.getByUserName(username);

        if (user == null) {
            throw new UserNotExistsException();
        }

        if (!ConfigConstants.ENABLE.equals(user.getStatus())) {
            throw new UserBlockedException();
        }

        if (!matches(user, password)) {
            throw new UserPasswordNotMatchException();
        }

        return user;
    }

    public boolean matches(SysUser user, String newPassword) {
        return user.getPassword().equals(encryptPassword(user.getUserName(), newPassword, user.getSalt()));
    }

    public String encryptPassword(String username, String password, String salt) {
        return new Md5Hash(username + password + salt).toHex();
    }

}
